//
//  WebViewViewController.m
//  Init
//
//  Created by zhaoshijie on 20/01/2018.
//  Copyright © 2018 zhaoshijie. All rights reserved.
//

#import "EBMBaseWebViewViewController.h"
//#import "SJDataManageTool.h"
//#import "EBMWechatManagerSingle.h"
#import "EBMUtilHeader.h"



@interface EBMBaseWebViewViewController ()

@end

@implementation EBMBaseWebViewViewController

// 记得取消监听
- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"title"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
}

/**
 初始化方法
 
 @param urlString 网址
 @param titleString 标题
 @return 对象
 */
- (instancetype)initWithUrlString:(NSString *)urlString
                      titleString:(NSString *)titleString
{
    self = [super init];
    if(self)
    {
        self.urlString = urlString;
        self.titleString = titleString;
    }
    return self;
}

/**
 初始化方法
 
 @param urlString 网址
 @param titleString 标题
 @param type 类型
 @return 对象
 */
- (instancetype)initWithUrlString:(NSString *)urlString
                      titleString:(NSString *)titleString
                             type:(WebViewType)type
{
    self = [super init];
    if(self)
    {
        self.urlString = urlString;
        self.titleString = titleString;
        self.webViewType = type;
    }
    return self;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    
    
    
    if(self.urlString)
    {
        
        //  初始化视图
        [self baseWebViewInitView];
        
        //  加载网页
        [self baseWebViewLoadWebView];
        
    }
}


#pragma mark ----------初始化视图----------
//  初始化视图
- (void)baseWebViewInitView
{
    
    //  设置导航栏内容
    [self baseWebViewSetNavigationContent];
    
    //  创建控件    webView
    [self baseWebViewCreateViewInWebView];
    
    //  创建控件    进度条
    [self baseWebViewCreateViewInProgress];
    
}


//  设置导航栏内容
- (void)baseWebViewSetNavigationContent
{
    self.navigationItem.title = self.titleString ? self.titleString : @"";
    
    if(self.webViewType == WebViewType_Service)
    {
        //  创建控件    右侧按钮

    }
    else if (self.webViewType == WebViewType_Share)
    {
        //  分享
        
    }
    
    
    //  创建控件    创建返回按钮
    [self baseWebViewCreateViewInBack];
    
}



//  创建控件    webView
- (void)baseWebViewCreateViewInWebView
{
    
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    // 创建UserContentController（提供JavaScript向webView发送消息的方法）
    self.userContent = [[WKUserContentController alloc] init];
    // 添加消息处理，注意：self指代的对象需要遵守WKScriptMessageHandler协议，结束时需要移除
    [self.userContent addScriptMessageHandler:self name:@"login"];
    [self.userContent addScriptMessageHandler:self name:@"webshare"];
    
    // 将UserConttentController设置到配置文件
    config.userContentController = self.userContent;

    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight-KNavigationBarAndStatusBarHeight-KBottomSurplusHeight) configuration:config];
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    [self.view insertSubview:self.webView belowSubview:self.progressView];
    
    // 添加KVO监听
    [self.webView addObserver:self
                     forKeyPath:@"title"
                        options:NSKeyValueObservingOptionNew
                        context:nil];
    [self.webView addObserver:self
                     forKeyPath:@"estimatedProgress"
                        options:NSKeyValueObservingOptionNew
                        context:nil];

}

//  创建控件    进度条
- (void)baseWebViewCreateViewInProgress
{
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0)];
    self.progressView.tintColor = [UIColor orangeColor];
    self.progressView.trackTintColor = [UIColor whiteColor];
    [self.view addSubview:self.progressView];
    
}



//  创建控件    创建返回按钮
- (void)baseWebViewCreateViewInBack
{
    
    
    [self.nvigationLetfBarButtonItemsMArray removeAllObjects];
    
    [self baseCreateViewInNavigationBarLeftButtonWtihTitle:nil imageName:@"Navigation_Back" buttonClickBlock:^{
    
        if (self.webView.canGoBack)
        {
            //  返回上一层
            [self.webView goBack];
            
        }else
        {
            [self.navigationController popViewControllerAnimated:YES];
            
            if(self.operationBlock)
            {
                self.operationBlock();
            }
        }
        
    }];
    
    if(self.webView.canGoBack)
    {
        //  按钮
        UIButton *closeWebLeftButton = [UIButton buttonWithType:UIButtonTypeCustom];
        closeWebLeftButton.frame = CGRectMake(0, 0, 40, 40);
        closeWebLeftButton.titleLabel.font = Font_14;
        [closeWebLeftButton setTitleColor:RGBACOLOR16_fffff_80 forState:UIControlStateNormal];
        [closeWebLeftButton setTitle:@"关闭" forState:UIControlStateNormal];
        
        
        closeWebLeftButton.imageEdgeInsets = UIEdgeInsetsMake(0, -18, 0, 0);
        [closeWebLeftButton addTarget:self action:@selector(baseWebViewCloseWebLeftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:closeWebLeftButton];
        
        [self.nvigationLetfBarButtonItemsMArray addObject:barButtonItem];
        
        self.navigationItem.leftBarButtonItems = self.nvigationLetfBarButtonItemsMArray;
        
    }
    
    
}




#pragma mark --------------方法--------------

//  加载网页
- (void)baseWebViewLoadWebView
{
    
    //  设置网页的请求头
    
    /*
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlString]];
    
    GTBUserSingle *userSingle = [GTBUserSingle shareUserSingle];
    
    //  设置网页请求头
    if([userSingle isLogin])
    {
  
        [request addValue:userSingle.token forHTTPHeaderField:@"token"];
        [request addValue:userSingle.mobile forHTTPHeaderField:@"mobile"];
        
        NSString *version = [SJAppInformationTool gainApplicationVersion];
        
        [request addValue:version forHTTPHeaderField:@"version"];
        
    }
     
    
    //  加载网页
    [self.webView loadRequest:request];
     */
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlString]];
    
    //  加载网页
    [self.webView loadRequest:request];
    
}


//  网页加载完成，传递数据
- (void)baseWebViewWebLoadCompletionTransmitInformation
{
    
    /*
    //  传递userId
    
    NSString *userId = [GTBUserSingle shareUserSingle].userId;
    
    if(userId)
    {
        NSString *message = [NSString stringWithFormat:@"fn_userId(%@)",userId];
        [self.webView evaluateJavaScript:message completionHandler:nil];
    }
     */
    
    
}


#pragma mark --------------响应方法--------------


//  关闭
- (void)baseWebViewCloseWebLeftButtonClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
    if(self.operationBlock)
    {
        self.operationBlock();
    }
}



#pragma mark ----------WKWebView 代理方法----------


// 如果不添加这个，那么wkwebview跳转不了AppStore
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    if ([webView.URL.absoluteString hasPrefix:@"https://itunes.apple.com"])
    {

        [[UIApplication sharedApplication]openURL:navigationAction.request.URL options:@{} completionHandler:nil];

        decisionHandler(WKNavigationActionPolicyCancel);

    }
    else
    {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
    
    //  网页跳转地址拦截
//    NSString *requestUrl = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    
    
 
//    if ([[requestUrl lowercaseString] isEqualToString:[@"gtb://APP_RECHARGE" lowercaseString]]) {
//
//        //  进入充值界面
//        [self enterRechargeVCWithMoney:nil];
//
//    }
    
}

// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"title"])
    {
        //  设置导航栏标题
        self.titleString = self.webView.title;
        self.navigationItem.title = self.titleString;

    }
    else if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"])
    {
        //  设置进度条
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];

        if (newprogress == 1) {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];


        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}


// WKScriptMessageHandler       js掉用OC的方法
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message
{
    
    
}



//  网页加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    
    //  创建控件    创建返回按钮
    [self baseWebViewCreateViewInBack];
    
    //  网页加载完成，传递数据
    [self baseWebViewWebLoadCompletionTransmitInformation];
    
}

//  网页加载失败
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    
    //  创建控件    创建返回按钮
    [self baseWebViewCreateViewInBack];
    
//    [MBProgressHUDInLoading MBProgressHUDInTitleWithTitle:@"网页加载失败"];
    
}





@end
